# -*- coding: utf-8 -*-
from MySpi import *
import thosttraderapi as api
import configparser
import threading
import os
import time

#local config check check
if(os.path.exists("config.local.ini")):
	configfile = "config.local.ini"
else:
	configfile = "config.ini"


configins=configparser.ConfigParser()
configins.read(configfile)
#Addr
FrontAddr=configins['network']['tradefront']
#AuthInfo
APPID=configins['authinfo']['appid']
AUTHCODE=configins['authinfo']['authcode']
#LoginInfo
BROKERID=configins['baseinfo']['brokerid']
USERID=configins['baseinfo']['userid']
PASSWORD=configins['baseinfo']['password']
#search conf
TIMEOUTSEC=int(configins['searchopt']['timeoutsec'])

#OrderInfo
EXCHANGEID=configins['ordercon']['exid']
INSTRUMENTID=configins['ordercon']['instrid']
ORDERTYPE=configins['ordercon']['orprtype']
HEDGEFLAG=configins['ordercon']['hedgeflag']
LIMITPRICE=float(configins['ordercon']['limitprice'])
OFFSETFLAG=configins['ordercon']['offsetflag']
DIRECTION=configins['ordercon']['direction']
VOLUME=int(configins['ordercon']['volumetotorg'])
MINVOL=int(configins['ordercon']['minvol'])
STOPPRICE=float(configins['ordercon']['stopprice'])
VOLUMECONDITION=configins['ordercon']['volumecon']
CONTIGENCON=configins['ordercon']['contingencon']


#stressconfig
INSERTFREQ=float(configins['stressconfig']['insertfreq'])



#decorator
def run_time(func):
	def wrap(argv1):
		start_time = time.time()
		rt = func(argv1)
		end_time = time.time()
		print('used time:', (end_time - start_time) * 1000, 'ms')
		return rt
	return wrap

class CTradeApi(api.CThostFtdcTraderApi):
	def __init__(self):
		self.tspi=''
		self.tapi=''
		self.ctlevent=threading.Event()
		self.sessionid=""
		self.frontid=""
		self.timecalc={}
		self.refcount=0
		self.ORDERREF=""
		self.orderpathconfirm=False

	@run_time
	def start(self):
		self.tapi=api.CThostFtdcTraderApi.CreateFtdcTraderApi()
		self.tspi=CTradeSpi(self)
		self.tapi.RegisterFront(FrontAddr)
		self.tapi.RegisterSpi(self.tspi)
		self.tapi.SubscribePrivateTopic(api.THOST_TERT_QUICK)
		self.tapi.SubscribePublicTopic(api.THOST_TERT_QUICK)
		self.tapi.Init()
		self.ctlevent.wait(timeout = TIMEOUTSEC)
		if(self.ctlevent.isSet() == True):
			self.ctlevent.clear()
			return 0
		else:
			print("init failed, please check network env")
			return 233

	@run_time
	def ReqAuth(self):
		authfield = api.CThostFtdcReqAuthenticateField()
		authfield.BrokerID=BROKERID
		authfield.UserID=USERID
		authfield.AppID=APPID
		authfield.AuthCode=AUTHCODE
		self.tapi.ReqAuthenticate(authfield,0)
		PrintSendName("ReqAuthenticate")
		self.ctlevent.wait(timeout = TIMEOUTSEC)
		if(self.ctlevent.isSet() == True):
			self.ctlevent.clear()
			return 0
		else:
			return 233

	@run_time
	def ReqLogin(self):
		loginfield = api.CThostFtdcReqUserLoginField()
		loginfield.BrokerID=BROKERID
		loginfield.UserID=USERID
		loginfield.Password=PASSWORD
		loginfield.UserProductInfo="python dll"
		self.tapi.ReqUserLogin(loginfield,0)
		PrintSendName("ReqUserLogin")
		self.ctlevent.wait(timeout = TIMEOUTSEC)
		if(self.ctlevent.isSet() == True):
			self.ctlevent.clear()
			print("sessionid:", self.sessionid)
			print("frontid:", self.frontid)
			return 0
		else:
			return 233

	def ReqSettleCf(self):
		settleconfirm=api.CThostFtdcSettlementInfoConfirmField()
		settleconfirm.BrokerID=BROKERID
		settleconfirm.InvestorID=USERID
		self.tapi.ReqSettlementInfoConfirm(settleconfirm, 0)
		PrintSendName("ReqSettleCf")
		self.ctlevent.wait(timeout = TIMEOUTSEC)
		if(self.ctlevent.isSet() == True):
			self.ctlevent.clear()
			return 0
		else:
			return 233



	def ReqOrIn(self):
		self.ORDERREF = str(self.refcount).zfill(7) + "SP"
		pInOrder=api.CThostFtdcInputOrderField()
		pInOrder.BrokerID=BROKERID
		pInOrder.InvestorID=USERID
		pInOrder.OrderRef=self.ORDERREF
		pInOrder.UserID=USERID
		pInOrder.ExchangeID=EXCHANGEID
		pInOrder.InstrumentID=INSTRUMENTID
		pInOrder.Direction=DIRECTION
		pInOrder.LimitPrice=LIMITPRICE
		pInOrder.VolumeTotalOriginal=VOLUME
		pInOrder.OrderPriceType=ORDERTYPE
		pInOrder.ContingentCondition=CONTIGENCON
		pInOrder.CombOffsetFlag=OFFSETFLAG
		pInOrder.CombHedgeFlag=HEDGEFLAG
		pInOrder.TimeCondition=api.THOST_FTDC_TC_GFD
		pInOrder.VolumeCondition=VOLUMECONDITION
		pInOrder.MinVolume=MINVOL
		pInOrder.IsAutoSuspend=0
		pInOrder.StopPrice=STOPPRICE
		pInOrder.ForceCloseReason=api.THOST_FTDC_FCC_NotForceClose
		pInOrder.IsSwapOrder=0
		pInOrder.UserForceClose=0
		self.timecalc[self.ORDERREF] = [time.time(), 0, 0, 0, 0]
		self.tapi.ReqOrderInsert(pInOrder, 0)
		PrintSendName("ReqOrderInsert")
		print("currorderref:", self.ORDERREF)
		self.refcount += 1
		self.ctlevent.wait(timeout = TIMEOUTSEC)
		if(self.ctlevent.isSet() == True):
			self.ctlevent.clear()
			return self.timecalc[self.ORDERREF]
		else:
			return 233

#print func name
def PrintSendName(sendname):
	sendmsg = "send " + sendname + " ok"
	print(sendmsg)

